# -*- coding: UTF-8 -*-

from os import path
import arcpy
import arcpy.da as da
import arcpy.management
import arcpy.sa as sa

from threshold_check import find_threshold

arcpy.env.workspace = u"E:\\Data\\2024-spatial-analysis\\exp3\\data"

input_shp = u"河南省.shp"
input_raster = "f2012"
# year = 2012

for year in [2012]:
    city_list = list()
    with da.SearchCursor(input_shp, ["SHAPE@" ,"NAME", "Area%04d"%year]) as cursors:
        for fea_row in cursors:
            out_shp_fn = fea_row[1]+".shp"
            city_list.append(fea_row[1])
            # arcpy.FeatureClassToFeatureClass_conversion(fea_row[0], arcpy.env.workspace, out_shp_fn)
            # print(out_shp_fn+" is saved!")
            outExtractByMask = sa.ExtractByMask(input_raster, fea_row[0])
            out_raster_fn = path.join(arcpy.env.workspace, fea_row[1]+".tif")
            if path.isfile(out_raster_fn):
                arcpy.management.Delete(out_raster_fn)
            outExtractByMask.save(out_raster_fn)
            print(out_raster_fn+" is saved!")
            count_list = list()
            value_list = list()
            with da.SearchCursor(out_raster_fn, ["Value", "Count"]) as rows:
                for row in rows:
                    count_list.append(row[1])
                    value_list.append(row[0])
                value_threshold = find_threshold(value_list, count_list, fea_row[2])
                print(out_raster_fn, value_threshold)
                buildup_raster = sa.Con(outExtractByMask>=value_threshold, outExtractByMask, None)
                out_raster_yearly = path.join(arcpy.env.workspace, "%s%04d.tif"%(fea_row[1], year))
                if path.isfile(out_raster_yearly):
                    arcpy.management.Delete(out_raster_yearly)
                buildup_raster.save(out_raster_yearly)
        raster_list = ["%s%04d.tif"%(city, year) for city in city_list]
        in_rasters = ";".join(raster_list)
        arcpy.MosaicToNewRaster_management(in_rasters, arcpy.env.workspace, "%04d.tif"%year, number_of_bands=1)
            